<template>
  <div class="inventory-warning">
    <el-card class="search-card">
      <el-form :inline="true" :model="filter">
        <el-form-item label="显示 Top N">
          <el-input-number v-model="filter.topN" :min="1" :max="50" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadChart">刷新</el-button>
          <el-button @click="switchType">切换图形（当前：{{ chartTypeLabel }}）</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <div ref="chartRef" class="chart"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import api from '@/api/inventory_api.js';

const chartRef = ref(null);
let chart;

// 配置
const filter = ref({ topN: 10 });
const chartType = ref('pie'); // 'pie' | 'bar'
const chartTypeLabel = computed(() => (chartType.value === 'pie' ? '饼图' : '柱状图'));

// 工具：从后端 Result 或分页结果中提取列表
const pickListFromResult = (res) => {
  // 常见几种包装：
  // 1) {code, msg, data:[...]}
  // 2) {code, msg, data:{ data:[...], count:xxx }}  // 分页
  // 3) 直接就是数组
  if (!res) return [];
  if (Array.isArray(res)) return res;
  if (Array.isArray(res.data)) return res.data;
  if (res.data && Array.isArray(res.data.data)) return res.data.data;
  // 有些 axios 封装会返回 {data:原始后端Result}
  if (res.data && res.data.data && Array.isArray(res.data.data.data)) return res.data.data.data;
  return [];
};

// 工具：把后端行转成 {name, value}
const toNameValue = (rows) => {
  // 兼容 summary 返回 [{name:'苹果', value:120}] 或 [{name:'苹果', current_stock:120}]
  // 以及 page 返回包含 fruit_name / fruit_id / current_stock 的行
  return rows.map((r) => {
    const name = r.name ?? r.fruit_name ?? `#${r.fruit_id ?? '未知'}`;
    const value = Number(r.value ?? r.current_stock ?? 0) || 0;
    return { name: String(name), value };
  });
};

// 切换图形
const switchType = () => {
  chartType.value = chartType.value === 'pie' ? 'bar' : 'pie';
  loadChart();
};

// 载入数据并渲染
const loadChart = async () => {
  let seriesData = [];
  try {
    // 1) 优先调用后端汇总接口（如果你已按我们之前建议实现了 /api/inventory/summary）
    let sumRes = null;
    try {
      sumRes = await api.summary();
    } catch (_) {
      sumRes = null;
    }

    if (sumRes) {
      const list = pickListFromResult(sumRes);
      if (list.length > 0) {
        seriesData = toNameValue(list);
      }
    }

    // 2) 若无 summary 或 summary 为空，fallback：用分页数据前端聚合
    if (seriesData.length === 0) {
      const pageRes = await api.page({ current: 1, limit: 5000 }); // 拉大页
      const list = pickListFromResult(pageRes);

      const map = new Map();
      list.forEach((it) => {
        const name = it.fruit_name ?? `#${it.fruit_id ?? '未知'}`;
        const val = Number(it.current_stock ?? 0) || 0;
        map.set(name, (map.get(name) || 0) + val);
      });
      seriesData = Array.from(map.entries()).map(([name, value]) => ({ name, value }));
    }

    // 排序 & TopN
    seriesData.sort((a, b) => (b.value || 0) - (a.value || 0));
    if (filter.value.topN && seriesData.length > filter.value.topN) {
      seriesData = seriesData.slice(0, filter.value.topN);
    }

    // 空数据处理
    if (seriesData.length === 0 || seriesData.every(i => !i.value)) {
      ElMessage.warning('暂无库存数据用于统计');
    }

    renderChart(seriesData);
  } catch (e) {
    console.error(e);
    ElMessage.error('加载库存统计失败');
    renderChart([]); // 也给个空图，避免白屏
  }
};

const renderChart = (data) => {
  if (!chart) {
    chart = echarts.init(chartRef.value);
    window.addEventListener('resize', resize);
  }

  if (chartType.value === 'pie') {
    chart.setOption({
      tooltip: { trigger: 'item' },
      legend: { top: '2%', left: 'center' },
      series: [
        {
          name: '库存占比',
          type: 'pie',
          radius: ['30%', '70%'],
          avoidLabelOverlap: true,
          itemStyle: { borderRadius: 8, borderColor: '#fff', borderWidth: 2 },
          label: { show: true, formatter: '{b}: {d}%' },
          data
        }
      ]
    });
  } else {
    chart.setOption({
      tooltip: { trigger: 'axis' },
      grid: { left: 40, right: 20, top: 40, bottom: 60 },
      xAxis: { type: 'category', data: data.map(i => i.name), axisLabel: { interval: 0, rotate: 30 } },
      yAxis: { type: 'value', name: '库存' },
      series: [{ type: 'bar', data: data.map(i => i.value) }]
    });
  }
};

const resize = () => chart && chart.resize();

onMounted(() => {
  loadChart();
});
onBeforeUnmount(() => {
  window.removeEventListener('resize', resize);
  chart && chart.dispose();
});
</script>

<style scoped>
.inventory-warning { padding: 20px; }
.search-card { margin-bottom: 16px; }
.chart { width: 100%; height: 520px; }
</style>
